package cn.edu.scau.dormitory_management_system.config;

import cn.edu.scau.dormitory_management_system.entity.SysLogEntity;
import cn.edu.scau.dormitory_management_system.entity.dto.LogDTO;
import cn.edu.scau.dormitory_management_system.service.SysLogService;
import cn.edu.scau.dormitory_management_system.service.impl.SysLogServiceImpl;
import cn.edu.scau.dormitory_management_system.util.SpringUtils;
import cn.edu.scau.dormitory_management_system.util.StringUtils;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;

import java.util.Date;

/**
 * @author djc
 * @date 2021/8/3
 * @time 15:41
 */

public class SpyConfig implements MessageFormattingStrategy {

    @Override
    public String formatMessage(int i, String now, long ms,
                                String s1, String s2, String s3, String s4) {
        if(StringUtils.isEmpty(s3)) return "";
        if(s3.contains("log") || s3.contains("record")) return "";
        if(s3.contains("tb_user") && !s3.contains("tb_user_role")) return "";
        if(s3.charAt(0) == 's' || s3.charAt(0) == 'S') return "";

        SysLogService service = SpringUtils.getBean("sysLogServiceImpl", SysLogServiceImpl.class);
        LogDTO logDTO = SpringUtils.getBean("logDTO", LogDTO.class);
        if(logDTO.isCan()) {
            SysLogEntity logEntity = new SysLogEntity();
            logEntity.setIpAddr(logDTO.getIp());
            logEntity.setCity(logDTO.getCity());
            logEntity.setUserName(logDTO.getUserName());
            logEntity.setExeTime(ms);
            logEntity.setOperation(StringUtils.getOperation(s3));
            logEntity.setOpTime(new Date());
            service.save(logEntity);
        }
        return "";
    }

}
